package com.xuecheng.framework.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 这个是读取指定文件，自动生成批量修改sql语句
 * 读取的文件第一个字段是表名称，弟二个是指定的id
 */
public class CreateMapperSQLBatchUpdate {

    public static void main(String[] args){

        //指定读取配置文件的路径
        String readerPath = "C:\\Users\\admin\\Desktop\\新建文本文档 (2).txt";
        //指定生成sql的文件路径
        String writerPath = "C:\\Users\\admin\\Desktop\\BatchUpdate.sql";
        try {

            //读取文件数据
            File file  = new File(readerPath);
            FileInputStream fileInputStream = new FileInputStream (file);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
            BufferedReader br = new BufferedReader(inputStreamReader);

            List<String> lines = new ArrayList<>();
            String line = "";
            while ((line = br.readLine()) != null){
                lines.add(line);
                System.out.println(line);
            }
            if(lines.size()<3){ //当不足三个字段时关闭程序
                System.exit(0);
            }

            //生成sql文件
            File createFile = new File(writerPath);
            if(createFile.exists()){
                createFile.delete();
            }
            createFile.createNewFile();
            FileOutputStream fileOutputStream = new FileOutputStream(createFile);
            OutputStreamWriter outputStream = new OutputStreamWriter(fileOutputStream);
            BufferedWriter bw = new BufferedWriter(outputStream);

            //生成前缀
            String prefix = createpPrefix(lines.get(0));
            bw.write(prefix);

            //生成中间部分
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 2; i < lines.size(); i++) {
                String data = lines.get(i);
                String idField = lines.get(1);
                String result = createMiddle(data,idField);
                stringBuffer.append(result);
            }
            bw.write(stringBuffer.toString());

            //生成尾部
            String suffix = createSuffix(lines.get(1));
            bw.write(suffix);

            bw.flush();
            bw.close();
            outputStream.close();
            fileOutputStream.close();
            br.close();
            inputStreamReader.close();
            fileInputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * sql语句的前缀
     * @return
     */
    public static String createpPrefix (String tableName){
        String prefixSql = "<update id=\"batchUpdate\" parameterType=\"??????\">\n" +
                "\t\tupdate "+ tableName +"\n" +
                "\t\t<trim prefix=\"set\" suffixOverrides=\",\">\n";
        return prefixSql;
    }

    /**
     * 拼接中间部分
     * @return
     */
    public static String createMiddle(String field , String idField){

        String param = camel4underline(field);

        String idParam = camel4underline(idField);

        String middle = "\t\t\t<trim prefix=\""+ param +" = case\" suffix=\"end,\">\n" +
                "\t\t\t\t<foreach collection=\"list\" item=\"item\" index=\"index\">\n" +
                "\t\t\t\t\t<if test=\"item."+ field +" != null  and item."+ field +" != ''\">when "+ idParam +" = #{item." + idField +"} then #{item."+ field +"}</if>\n" +
                "\t\t\t\t</foreach>\n" +
                "\t\t\t</trim>\n";

        return middle;
    }

    /**
     * 拼接结尾部分的条件
     * @param idField
     * @return
     */
    public static String createSuffix(String idField){

        String idParam = camel4underline(idField);

        String suffix = "\t\t</trim>\n" +
                "\t\twhere "+ idParam +" in\n" +
                "\t\t<foreach collection=\"list\" index=\"index\" item=\"item\" separator=\",\" open=\"(\" close=\")\">\n" +
                "\t\t\t#{item."+ idField +"}\n" +
                "\t\t</foreach>\n" +
                "\t</update>";
        return suffix;
    }

    /**
     * 大写字母转为下划线加小写
     * @param param
     * @return
     */
    public static String camel4underline(String param){
        Pattern p=Pattern.compile("[A-Z]");
        if(param==null ||param.equals("")){
            return "";
        }
        StringBuilder builder=new StringBuilder(param);
        Matcher mc=p.matcher(param);
        int i=0;
        while(mc.find()){
            builder.replace(mc.start()+i, mc.end()+i, "_"+mc.group().toLowerCase());
            i++;
        }

        if('_' == builder.charAt(0)){
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }


}